package com.woniuxy.file.controller;

import com.aliyun.oss.OSSClient;
import com.woniuxy.commons.enums.ResultEnum;
import com.woniuxy.commons.util.ResponseResult;
import com.woniuxy.file.entity.UploadResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;

/**
 * @Author: yangtao
 * @date 2021/8/6 15:22
 * @Version 1.0
 */
@RestController
@RequestMapping("/file")
public class FileController {
    //springboot自动配置好
    @Resource
    private OSSClient ossClient;
    private String bucketName="ytspringcloud-79";
    private String baseUrl="https://ytspringcloud-79.oss-cn-chengdu.aliyuncs.com/";
    @PostMapping("/upload")
    public ResponseResult upload(MultipartFile file) throws IOException {
        String filename = file.getOriginalFilename();
        //1、获取文件流对象
        InputStream inputStream = file.getInputStream();
        //2、将流设置到ossclient对象上
        ossClient.putObject(bucketName,filename,inputStream);
        //3、设置文件过期的时间
        Date date = new Date(new Date().getTime() + 30 * 24 * 3600 * 1000);
        URL url = ossClient.generatePresignedUrl(bucketName, filename, date);

        //4、上传到阿里云，返回结果
        UploadResult result = new UploadResult(filename, baseUrl+filename);
        return new ResponseResult(200, ResultEnum.SYSTEM_SUCCESS,"上传成功",result);
    }
}
